package com.zeng.createmd.restfulmodule.convert;

import com.zeng.plugin.entity.RowEntity;
import com.zeng.plugin.entity.TableEntity;
import com.zeng.plugin.util.HumpStringUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class TableEntityConvertor {

    public TableEntity mapToTableEntity(Map<String, Object> map) {
        TableEntity tableEntity = new TableEntity();
        tableEntity.setRealTableName((String)map.get("tableName"));
        tableEntity.setAuthor((String)map.get("auth"));
        tableEntity.setClassName(HumpStringUtil.humpStringHandle((String) map.get("tableName"), "_"));
        tableEntity.setDesc((String)map.get("desc"));
        tableEntity.setRows(toRowEntity((List<Map<String, String>>)map.get("fields")));
        return tableEntity;
    }

    public List<RowEntity> toRowEntity(List<Map<String, String>> fields) {
        if (fields == null) {
            throw new RuntimeException("fields 参数不能为空");
        }
        ArrayList<RowEntity> rowEntities = new ArrayList<>();
        for (Map<String, String> field : fields) {
            RowEntity rowEntity = new RowEntity();
            rowEntity.setDesc(field.get("desc"));
            int length = Integer.valueOf(field.get("length"));
            if (length != 0) {
                rowEntity.setLength(length);
            }
            rowEntity.setName(field.get("fieldName"));
            setType(rowEntity, field.get("type"));
            rowEntities.add(rowEntity);
        }
        return rowEntities;
    }

    public void setType(RowEntity rowEntity, String type) {
        switch (type) {
            case "varchar":
                rowEntity.setType(String.class);
                break;
            case "Text":
                rowEntity.setType(String.class);
                break;
            case "BigDecimal":
                rowEntity.setType(BigDecimal.class);
                break;
            case "Short":
                rowEntity.setType(Short.class);
                break;
            case "Long":
                rowEntity.setType(Long.class);
                break;
            case "Date":
                rowEntity.setType(Date.class);
                break;
            case "Integer":
                rowEntity.setType(Integer.class);
                break;
        }
    }
}
